using System;
using System.Collections.Concurrent; // ConcurrentDictionary需要
using System.Collections.Generic;
using System.IO.Ports;  // SerialPort需要
using System.Threading; // Thread需要
using System.Windows;   // Dispatcher需要

public class MessageBroker
{
    private static readonly Lazy<MessageBroker> _instance = 
        new Lazy<MessageBroker>(() => new MessageBroker());
    
    private readonly ConcurrentDictionary<string, List<Action<object>>> _topics = 
        new ConcurrentDictionary<string, List<Action<object>>>();

    public static MessageBroker Default => _instance.Value;

    // 订阅主题
    public void Subscribe<T>(string topic, Action<T> callback)
    {
        var wrapper = new Action<object>(obj =>
        {
            if (obj is T typedObj)
            {
                if (Application.Current.Dispatcher.CheckAccess())
                {
                    callback(typedObj);
                }
                else
                {
                    Application.Current.Dispatcher.Invoke(() => callback(typedObj));
                }
            }
        });

        _topics.AddOrUpdate(topic,
            new List<Action<object>> { wrapper },
            (_, existingList) =>
            {
                existingList.Add(wrapper);
                return existingList;
            });
    }

    // 发布消息
    public void Publish(string topic, object message)
    {
        if (_topics.TryGetValue(topic, out var callbacks))
        {
            foreach (var callback in callbacks.ToArray()) // ToArray防止迭代时修改
            {
                callback(message);
            }
        }
    }

    // 取消订阅（需保留引用）
    public void Unsubscribe(string topic, Action<object> callback)
    {
        if (_topics.TryGetValue(topic, out var callbacks))
        {
            callbacks.Remove(callback);
        }
    }
}